package com.imflea.zero.service.share.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imflea.zero.model.dao.share.ShareConfigMapper;
import com.imflea.zero.model.entity.share.ShareConfig;
import com.imflea.zero.model.entity.share.dto.PosterDto;
import com.imflea.zero.model.entity.share.dto.ShareAttachmentDto;
import com.imflea.zero.model.entity.share.dto.ShareConfigDto;
import com.imflea.zero.model.entity.share.vo.QueryPageVo;
import com.imflea.zero.service.share.IShareConfigService;
import com.imflea.zero.util.base.CommonUtils;
import com.imflea.zero.utils.SessionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 分享界面图片配置表 服务实现类
 * </p>
 *
 * @author guohui
 * @since 2021-10-21
 */
@Service
public class ShareConfigServiceImpl extends ServiceImpl<ShareConfigMapper, ShareConfig> implements IShareConfigService {

    @Override
    public ShareConfigDto saveOrUpdateShareConfig(ShareConfigDto entity) {
        if (CommonUtils.isNull(entity.getId()))
            entity.setId(CommonUtils.generateRandomString());
        if (CommonUtils.isNull(entity.getList()))
            return null;
        if (CommonUtils.isNull(entity.getBusinessId())) {
            entity.setBusinessId(CommonUtils.generateRandomString());
        } else { //按照business_id 全量删除，全量插入
            this.deleteBatchByBusinessId(entity.getBusinessId());
        }
        List<ShareConfig> result = this.dtoToEntity(entity);
        this.saveBatch(result);
        return entity;
    }

    /**
     * ShareConfigDto 转 List<ShareConfig>
     */
    private List<ShareConfig> dtoToEntity(ShareConfigDto dto) {
        if (CommonUtils.isNull(dto) || CommonUtils.isNull(dto.getList())) return null;
        List<ShareConfig> result = new ArrayList<>();
        dto.getList().forEach((item) -> {
            ShareConfig shareConfig = new ShareConfig();
            BeanUtils.copyProperties(dto, shareConfig);
            shareConfig.setTenantId(SessionUtils.getTenantId());
            shareConfig.setPic(item.getIcon());
            shareConfig.setUri(item.getUri());
            shareConfig.setAttachmentId(item.getAttachmentId());
            shareConfig.setId(CommonUtils.generateRandomString());
            shareConfig.setSort(item.getSort());
            result.add(shareConfig);
        });
        return result;
    }

    private boolean deleteBatchByBusinessId(String pam) {
        QueryWrapper<ShareConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("business_id", pam);
        queryWrapper.eq("tenant_id", SessionUtils.getTenantId());
        return this.remove(queryWrapper);
    }

    @Override
    public PageInfo<QueryPageVo> queryPage(ShareConfigDto pam) {
        String title = pam.getTitle();

        List<ShareConfig> shareConfigs = this.queryList(pam.getPageNum(), pam.getPageSize(), title);
        if (CommonUtils.isNull(shareConfigs)) {
            return new PageInfo<>(new ArrayList<>());
        }
        List<QueryPageVo> result = this.shareConfigDtoToQueryPageVoList(shareConfigs);
        //参数对象封装
        List<String> businessIds = new ArrayList<>();
        shareConfigs.forEach(item -> businessIds.add(item.getBusinessId()));
        List<ShareConfig> list = this.listByBusinessIds(businessIds);
        result.forEach(res ->
                list.forEach((item) -> {
                    if (res.getBusinessId().equals(item.getBusinessId())) {
                        ShareAttachmentDto shareAttachmentDto = new ShareAttachmentDto();
                        shareAttachmentDto.setId(item.getId());
                        shareAttachmentDto.setUri(item.getUri());
                        shareAttachmentDto.setSort(item.getSort());
                        shareAttachmentDto.setIcon(item.getPic());
                        shareAttachmentDto.setAttachmentId(item.getAttachmentId());
                        res.getList().add(shareAttachmentDto);
                    }
                })
        );
        return new PageInfo<>(result);
    }

    @Override
    public ShareConfig queryByBusinessId(String id) {
        List<ShareConfig> list = this.baseMapper.listByMaxSort(id, SessionUtils.getTenantId());
        if (CommonUtils.isNull(list)) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public String poster(PosterDto pam) throws Exception {

        return null;
    }


    /**
     * 根据businessIds查找列表
     */
    private List<ShareConfig> listByBusinessIds(List<String> pam) {
        QueryWrapper<ShareConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tenant_id", SessionUtils.getTenantId());
        queryWrapper.in("business_id", pam);
        queryWrapper.orderByAsc("sort");
        return this.list(queryWrapper);
    }

    /**
     * 将shareConfigs转换为 List<QueryPageVo>
     */
    private List<QueryPageVo> shareConfigDtoToQueryPageVoList(List<ShareConfig> pam) {
        List<QueryPageVo> result = new ArrayList<>(pam.size());
        pam.forEach((item) -> {
            QueryPageVo queryPageVo = new QueryPageVo();
            BeanUtils.copyProperties(item, queryPageVo);
            result.add(queryPageVo);
        });
        return result;
    }

    /**
     * 根据分页参数查list
     */
    private List<ShareConfig> queryList(Integer pageIndex, Integer pageSize) {
        String tenantId = SessionUtils.getTenantId();
        QueryWrapper<ShareConfig> queryWrapper = new QueryWrapper<>();
        if (!CommonUtils.isNull(tenantId)) {
            queryWrapper.eq("tenant_id", tenantId);
        }
        queryWrapper.orderByAsc("sort");
        queryWrapper.groupBy("business_id");
        PageHelper.startPage(pageIndex, pageSize);
        return this.list(queryWrapper);
    }

    /**
     * 根据分页参数查list
     */
    private List<ShareConfig> queryList(Integer pageIndex, Integer pageSize, String title) {

        String tenantId = SessionUtils.getTenantId();
        QueryWrapper<ShareConfig> queryWrapper = new QueryWrapper<>();
        if (!CommonUtils.isNull(tenantId)) {
            queryWrapper.eq("tenant_id", tenantId);
        }
        if (!CommonUtils.isNull(title)) {
            queryWrapper.like("title", title);
        }
        queryWrapper.orderByAsc("sort");
        queryWrapper.groupBy("business_id");
        PageHelper.startPage(pageIndex, pageSize);
        return this.list(queryWrapper);

    }
}
